package com.wgz.flag.service.impl;

import com.wgz.flag.domain.dto.LoginDto;
import com.wgz.flag.domain.dto.RegisterDto;
import com.wgz.flag.domain.dto.ResetPasswordDto;
import com.wgz.flag.domain.vo.UserLoginVo;
import com.wgz.flag.entity.User;
import com.wgz.flag.exception.BaseException;
import com.wgz.flag.mapper.UserMapper;
import com.wgz.flag.service.UserService;
import com.wgz.flag.utils.JwtUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import jakarta.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.UUID;

/**
 * 用户服务实现类
 * 处理用户注册、登录、信息修改等功能
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private JwtUtil jwtUtil;
    @Value("${file.upload.path}")
    private String uploadPath;
    @Value("${file.upload.avatar-path}")
    private String avatarPath;
    @Autowired
    private HttpServletRequest request;

    @Override
    public List<User> getAllUsers(User user) {
        return userMapper.findAll(user);
    }

    /**
     * 用户登录
     * 1. 验证用户名密码
     * 2. 生成token
     * 3. 返回用户信息
     */
    @Override
    public UserLoginVo login(LoginDto loginDto) {
        // 1.获取前端传来的数据
        String username = loginDto.getUsername();
        String password = loginDto.getPassword();
        // 2.根据用户名查询数据
        List<User> users = userMapper.findByUsername(username);
        if (users.isEmpty() && users.size() == 0) {
            throw new BaseException("用户名不存在");
        }
        // 3.校验密码
        User user = users.get(0);
        if (!password.equals(user.getPassword())) {
            throw new BaseException("密码错误");
        }
        // 5.封装token
        String token = jwtUtil.generateToken(user.getUsername());
        UserLoginVo userLoginVo = new UserLoginVo();
        userLoginVo.setId(user.getId());
        userLoginVo.setUsername(user.getUsername());
        userLoginVo.setNickname(user.getNickname());
        userLoginVo.setAvatar(user.getAvatar());
        userLoginVo.setToken(token);
        // 6.返回结果
        return userLoginVo;
    }

    @Override
    public void register(RegisterDto registerDto) {
        User user = new User();
        // 将dto中的数据拷贝到user中
        BeanUtils.copyProperties(registerDto, user);
        user.setAge(18);
        userMapper.insert(user);
    }

    @Override
    public List<User> getAllUserInfo() {
        return userMapper.getAll();
    }

    @Override
    public User selectById(Long id) {
        return userMapper.selectById(id);
    }

    @Override
    public void updateUserInfo(User user) {
        // 检查用户ID是否为空
        if (user.getId() == null) {
            throw new IllegalArgumentException("User ID 不能为空");
        }
        User user1 = userMapper.selectById(user.getId());
        // 检查用户是否存在
        if (user1 == null) {
            throw new NoSuchElementException("User with ID " + user.getId() + " 不存在");
        }

        user1.setUsername(user.getUsername());
        user1.setNickname(user.getNickname());
        user1.setEmail(user.getEmail());
        user1.setPhone(user.getPhone());
        user1.setAge(user.getAge());
        user1.setUpdateTime(LocalDateTime.now());
        userMapper.updateById(user1);
    }

    @Override
    public String uploadAvatar(MultipartFile file) {
        try {
            String fileName = "avatar_" + getCurrentUserId() + "_" +
                    file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));

            File dest = new File(avatarPath + fileName);
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            file.transferTo(dest);

            // 返回完整的URL，包含后端服务器地址
            String avatarUrl = "http://localhost:8080/file/uploads/avatar/" + fileName;

            // 更新用户头像
            User user = userMapper.selectById(getCurrentUserId());
            user.setAvatar(avatarUrl);
            userMapper.updateById(user);

            return avatarUrl;
        } catch (IOException e) {
            throw new RuntimeException("头像上传失败", e);
        }
    }

    /**
     * 修改密码
     * @param resetPasswordDto 重置密码的参数
     */
    @Override
    public void updateUserPassword(ResetPasswordDto resetPasswordDto) {
        User user = userMapper.selectById(resetPasswordDto.getUserId());
        if(user == null ){
            throw new BaseException("用户不存在");
        }
        if(!user.getPassword().equals(resetPasswordDto.getOldPassword())){
            throw new BaseException("旧密码错误");
        }
        user.setPassword(resetPasswordDto.getNewPassword());
        userMapper.updateById(user);
    }

    private Long getCurrentUserId() {
        String token = request.getHeader("Authorization");
        if (token == null) {
            throw new BaseException("未登录");
        }

        // 如果 token 以 "Bearer " 开头，去掉这个前缀
        if (token.startsWith("Bearer ")) {
            token = token.substring(7);
        }

        try {
            String username = jwtUtil.getUsernameFromToken(token);
            List<User> users = userMapper.findByUsername(username);
            if (users.isEmpty()) {
                throw new BaseException("用户不存在");
            }
            return users.get(0).getId();
        } catch (Exception e) {
            throw new BaseException("token无效");
        }
    }
}